﻿using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;

namespace Micro.Extensions.Cache.Redis
{
    public class RedisConfig : BaseConfiguration, IOptions<RedisConfig>
    {
        /// <summary>
        /// 默认超时时间
        /// </summary>
        public int ConnectTimeout { get; set; } = 3000;

        /// <summary>
        /// 用于标识连接Redis的客户端名称（自定义）
        /// </summary>
        public string ClientName { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; } = "";

        /// <summary>
        /// Redis服务端地址列表，以","分隔，例："192.168.1.1:6379,192.168.1.2:6379"
        /// </summary>
        public string Endpoints { get; set; }

        /// <summary>
        /// 是否允许Admin操作
        /// </summary>
        public bool AllowAdmin { get; set; } = false;

        /// <summary>
        /// 缓存前缀配置,不能超过20个字符
        /// </summary>
        public string Prefix { get; set; }

        /// <summary>
        /// 发送消息以帮助保持套接字活动的时间, 即连接保持时间（默认60s）
        /// </summary>
        public int KeepAlive { get; set; } = 60;

        /// <summary>
        /// 指定系统允许同步操作的时间(默认为1秒)，以毫秒为单位
        /// </summary>
        public int SyncTimeout { get; set; } = 1000;


        private int? _asyncTimeout;

        /// <summary>
        /// 指定系统允许异步操作的时间(默认为SyncTimeout)，以毫秒为单位
        /// </summary>
        public int AsyncTimeout
        {
            get => _asyncTimeout ?? SyncTimeout;
            set => _asyncTimeout = value;
        }

        [JsonIgnore]
        public RedisConfig Value => this;
    }

    /// <summary>
    /// 服务端节点信息
    /// </summary>
    public class ServerEndPoint
    {
        public ServerEndPoint(string host, int port)
        {
            if (string.IsNullOrWhiteSpace(host))
                throw new ArgumentNullException(nameof(host));

            Host = host;
            Port = port;
        }

        public ServerEndPoint()
        {
        }

        /// <summary>
        /// 端口号
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// Host地址
        /// </summary>
        public string Host { get; set; }
    }
}
